//
//  UploadFileView.swift
//  miaoyin
//
//  Created by David on 2017/3/1.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

enum FCPrintPaperType {
    case blackWhiteSingle
    case colorSingle
    case blackWhiteDouble
    case colorDouble
}

class UploadFileView: UIView {

    var delegate: CardViewDelegate?
    
    var fileIcon: UIImageView!
    var fileNameLabel: UILabel!
    var filePageLabel: UILabel!
    var fileSizeLabel: UILabel!
    
    var duplexOption: UISegmentedControl!
    var bwOption: UISegmentedControl!
    
    var minusBtn: UIButton!
    var addBtn : UIButton!
    var countInput: UITextField!
    
    var nextBtn: UIButton!
    
    var quantity = 1
    
    var retryBtn: UIButton!
    
    var paperOption: FCPrintPaperType{
        let bw = bwOption.selectedSegmentIndex
        let sd = duplexOption.selectedSegmentIndex
        
        if bw == 0 && sd == 0{
            return .blackWhiteSingle
        }else if bw == 1 && sd == 0{
            return .colorSingle
        }else if bw == 0 && sd == 1{
            return .blackWhiteDouble
        }else if bw == 1 && sd == 1{
            return .colorDouble
        }
        return .blackWhiteSingle
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        let bgView = UIVisualEffectView(frame: frame)
        bgView.effect = UIBlurEffect(style: .dark)
        addSubview(bgView)
        
        let blankCloseBtn = UIButton(frame: frame)
        bgView.addSubview(blankCloseBtn)
        blankCloseBtn.addTarget(self, action: #selector(UploadFileView.hideView), for: .touchUpInside)
        
        let cardView = UIView(frame: CGRect(x: 16, y: 0, width: frame.width - 32, height: 400))
        cardView.center = CGPoint(x: frame.width/2, y: frame.height/2)
        cardView.backgroundColor = UIColor.white
        cardView.layer.cornerRadius = 8
        bgView.addSubview(cardView)
        cardView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(UploadFileView.tapClose)))
        
        let stackView = UIStackView(frame: CGRect(x: 16, y: 16, width: cardView.frame.width - 32, height: cardView.frame.height - 32))
        stackView.axis = .vertical
        stackView.distribution = .fillEqually
        cardView.addSubview(stackView)
        
        
        let rowHeight = stackView.frame.width/9
        var viewsInStack:[UIView] = []
        for _ in 0..<9{
            let view = UIView(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: rowHeight))
            viewsInStack.append(view)
            stackView.addArrangedSubview(view)
        }
        
        //r1
        let r1View = UIView(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: rowHeight))
        viewsInStack[0].addSubview(r1View)
        
        fileIcon = UIImageView(frame: CGRect(x: 0, y: 8, width: 48, height: 48))
//        fileIcon.backgroundColor = UIColor.lightGray
        r1View.addSubview(fileIcon)
        fileIcon.image = #imageLiteral(resourceName: "doc_icon")
        
        fileNameLabel = UILabel(frame: CGRect(x: 56, y: 8, width: stackView.frame.width-56, height: 20))
        fileNameLabel.text = "文件名称.doc"
        fileNameLabel.lineBreakMode = .byTruncatingMiddle
        r1View.addSubview(fileNameLabel)
        
        filePageLabel = UILabel(frame: CGRect(x: 56, y: 36, width: (stackView.frame.width-56)/2, height: 20))
        filePageLabel.font = UIFont.systemFont(ofSize: 14)
        filePageLabel.textColor = UIColor.lightGray
        filePageLabel.text = "?页"
        r1View.addSubview(filePageLabel)
        
        fileSizeLabel = UILabel(frame: CGRect(x: (stackView.frame.width-56)/2 + 56, y: 36, width: (stackView.frame.width-56)/2, height: 20))
        fileSizeLabel.font = UIFont.systemFont(ofSize: 14)
        fileSizeLabel.textColor = UIColor.lightGray
        fileSizeLabel.textAlignment = .right
//        fileSizeLabel.text = "223.63KB"
        r1View.addSubview(fileSizeLabel)
        
        //r2
        let r2View = UIView(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: rowHeight))
        viewsInStack[2].addSubview(r2View)
        
        duplexOption = UISegmentedControl(items: ["单面", "双面"])
        duplexOption.frame = CGRect(x: 0, y: 0, width: (stackView.frame.width)/2 - 4, height: 28)
        duplexOption.selectedSegmentIndex = 0
        duplexOption.tintColor = themeColor1
        r2View.addSubview(duplexOption)
        
        bwOption = UISegmentedControl(items: ["黑白", "彩色"])
        bwOption.frame = CGRect(x: (stackView.frame.width)/2 + 4, y: 0, width: (stackView.frame.width)/2 - 4, height: 28)
        bwOption.selectedSegmentIndex = 0
        bwOption.tintColor = themeColor1
        r2View.addSubview(bwOption)
        
        //r3
        let r3View = UIView(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: rowHeight))
        viewsInStack[3].addSubview(r3View)
        
        let countLabel = UILabel(frame: CGRect(x: 0, y: 0, width: stackView.frame.width/2, height: rowHeight))
        countLabel.text = "打印份数"
//        countLabel.font = UIFont.systemFont(ofSize: 14)
        countLabel.textColor = themeColor2
        r3View.addSubview(countLabel)
        
        let countInputView = UIView(frame: CGRect(x: stackView.frame.width/2, y: 8, width: stackView.frame.width/2, height: 28))
        r3View.addSubview(countInputView)
        
        minusBtn = UIButton(frame: CGRect(x: 0, y: 0, width: countInputView.frame.width/2+8, height: 28))
        minusBtn.layer.borderColor = themeColor2.cgColor
        minusBtn.layer.borderWidth = 1
        minusBtn.layer.cornerRadius = 4
        minusBtn.setTitle("-", for: .normal)
        minusBtn.setTitleColor(themeColor2, for: .normal)
        minusBtn.setTitleColor(UIColor.lightGray, for: .disabled)
//        minusBtn.titleLabel?.textAlignment = .left
        minusBtn.contentHorizontalAlignment = .left
        minusBtn.titleLabel?.font = UIFont.systemFont(ofSize: 24)
        minusBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
        countInputView.addSubview(minusBtn)
        minusBtn.addTarget(self, action: #selector(UploadFileView.minusCount), for: .touchUpInside)
        minusBtn.isEnabled = false
        
        addBtn = UIButton(frame: CGRect(x: countInputView.frame.width/2, y: 0, width: countInputView.frame.width/2, height: 28))
        addBtn.layer.borderColor = themeColor2.cgColor
        addBtn.layer.borderWidth = 1
        addBtn.layer.cornerRadius = 4
        addBtn.setTitle("+", for: .normal)
        addBtn.setTitleColor(themeColor2, for: .normal)
        addBtn.setTitleColor(UIColor.lightGray, for: .disabled)
//        addBtn.titleLabel?.textAlignment = .left
        addBtn.contentHorizontalAlignment = .right
        addBtn.titleLabel?.font = UIFont.systemFont(ofSize: 24)
        addBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 16)
        countInputView.addSubview(addBtn)
        addBtn.addTarget(self, action: #selector(UploadFileView.addCount), for: .touchUpInside)
        
        
        countInput = UITextField(frame: CGRect(x: 0, y: 1, width: countInputView.frame.width/3.5, height: 26))
        countInput.center.x = countInputView.frame.width/2
        countInput.backgroundColor = UIColor.lightGray
        countInput.textAlignment = .center
        countInput.font = UIFont.systemFont(ofSize: 14)
        countInput.text = "1"
        countInput.keyboardType = .numberPad
        countInputView.addSubview(countInput)
        countInput.addTarget(self, action: #selector(UploadFileView.quantityUpdate), for: .editingChanged)
        countInput.addTarget(self, action: #selector(UploadFileView.quantityRestore), for: .editingDidEnd)
        
        //r4
        let r4View = UIView(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: rowHeight))
        viewsInStack[6].addSubview(r4View)
        
        nextBtn = UIButton(frame: CGRect(x: 0, y: 0, width: rowHeight, height: rowHeight))
        nextBtn.setImage(#imageLiteral(resourceName: "arrow_black"), for: .normal)
        nextBtn.center.x = stackView.frame.width/2
        nextBtn.isEnabled = false
        r4View.addSubview(nextBtn)
        
        //r5
        let r5View = UIView(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: rowHeight))
        viewsInStack[8].addSubview(r5View)
        
        let infoLabel = UILabel(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: rowHeight))
        infoLabel.textAlignment = .center
        infoLabel.textColor = UIColor.red
        infoLabel.text = "注：一次只能打印一个文件"
        infoLabel.font = UIFont.systemFont(ofSize: 14)
        r5View.addSubview(infoLabel)
        
        alpha = 0
    }
    
    var file: FCPrintFile?
    
    func showView(_ file: FCPrintFile){
//        alpha = 1
        
        nextBtn.isEnabled = false
        countInput.text = "1"
        quantity = 1
        minusBtn.isEnabled = false
        minusBtn.isEnabled = true
        self.file = file
        fileNameLabel.text = file.fileName
        self.duplexOption.setEnabled(true, forSegmentAt: 1)
        duplexOption.selectedSegmentIndex = 0
        bwOption.selectedSegmentIndex = 0
        
        var pageCorrect = false
        
        if file.filePage != nil{
            if file.filePage != "0" {
                pageCorrect = true
                nextBtn.isEnabled = true
                filePageLabel.text = "\(file.filePage!)页"
                if Int(file.filePage!) ?? 0 < 2 {
                    self.duplexOption.setEnabled(false, forSegmentAt: 1)
                }
            }
        }
        
        if !pageCorrect{
            getPage()
        }
        
        UIView.animate(withDuration: 0.3) {
            self.alpha = 1
        }
    }
    
    func getPage(){
        let url = URL(string: "\(apiBaseDomainName)?m=admin&c=goods&a=getPageNum&f=\(file?.fileID ?? "xxxx")")
        if url != nil{
            filePageLabel.text = "正在获取页数..."
            URLSession.shared.dataTask(with: url!, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                do{
                    if err != nil{
                        throw err!
                    }
                    print(String(data: data!, encoding: .utf8) ?? "data nil")
                    let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                    var pnum = jsonData?.object(forKey: "pNum") as? Int
                    
                    if pnum == nil {
                        let pnumStr = jsonData?.object(forKey: "pNum") as? String
                        if pnumStr != nil{
                            pnum = Int(pnumStr!)
                        }
                    }
                    
                    if pnum != nil{
                        DispatchQueue.main.async {
                            self.file?.filePage = "\(pnum!)"
                            self.nextBtn.isEnabled = true
                            self.filePageLabel.text = "\(pnum!)页"
                            
                            if pnum! < 2 {
                                self.duplexOption.setEnabled(false, forSegmentAt: 1)
                                
                            }
                        }
                    }else{
                        DispatchQueue.main.async {
                            self.filePageLabel.text = "获取失败"
                        }
                    }
                    
                }catch let ex{
                    DispatchQueue.main.async {
                        self.filePageLabel.text = "获取失败"
                    }
                    
                    print(ex)
                }
            }).resume()
        }
    }
    
    func hideView(){
        delegate?.cardViewClose?(self)
        countInput.resignFirstResponder()
//        alpha = 0
        UIView.animate(withDuration: 0.3) {
            self.alpha = 0
        }
        
    }
    
    func addCount(){
        countInput.resignFirstResponder()
        quantity += 1
        if quantity <= 1{
            minusBtn.isEnabled = false
        }else{
            minusBtn.isEnabled = true
        }
        if quantity >= 99 {
            addBtn.isEnabled = false
            if quantity >= 100 {
                quantity = 99
            }
        }else{
            addBtn.isEnabled = true
        }
        countInput.text = "\(quantity)"
    }
    
    func minusCount(){
        countInput.resignFirstResponder()
        quantity -= 1
        
        if quantity <= 1{
            minusBtn.isEnabled = false
            if quantity <= 0{
                quantity = 1
            }
        }else{
            minusBtn.isEnabled = true
        }
        if quantity >= 99 {
            addBtn.isEnabled = false
            if quantity >= 100 {
                quantity = 99
            }
        }else{
            addBtn.isEnabled = true
        }
        countInput.text = "\(quantity)"
    }
    
    func quantityUpdate(_ sender: UITextField){
        if sender.text != "" {
            if let quantity = Int(sender.text!) {
                if 0 < quantity && quantity < 100{
                    self.quantity = quantity
                    if quantity <= 1{
                        minusBtn.isEnabled = false
                    }else{
                        minusBtn.isEnabled = true
                    }
                    if quantity >= 99 {
                        addBtn.isEnabled = false
                    }else{
                        addBtn.isEnabled = true
                    }
                }
                
            }
            sender.text = "\(quantity)"
        }
        
    }
    func quantityRestore(_ sender: UITextField){
        if sender.text == "" {
            sender.text = "1"
            quantity = 1
            minusBtn.isEnabled = false
            
        }
    }
    
    func tapClose(){
        countInput.resignFirstResponder()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

class FCPrintFile: NSObject{
    var fileName: String?
    var fileSize: String?
    var filePage: String?
    var fileID: String?
    
    init(fileName: String?, fileSize: String?, filePage: String?, fileID: String?){
        self.fileName = fileName
        self.fileSize = fileSize
        self.filePage = filePage
        self.fileID = fileID
    }
}
